package com.sky.service.user.Impl;

import cn.hutool.db.sql.Order;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.config.ThreadConfig;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.controller.user.WxPayController;
import com.sky.dto.*;
import com.sky.exception.BaseException;
import com.sky.exception.ShopIDNotNULLException;
import com.sky.mapper.user.*;
import com.sky.pojo.*;
import com.sky.result.PageResult;
import com.sky.service.user.OrderService;
import com.sky.service.user.ShoppingCartService;
import com.sky.utils.MapUtils;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private TradeOrderMapper tradeOrderMapper;
    @Autowired
    private CourierMapper courierMapper;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ShoppingCartService shoppingCartService;


    @Override
    public String getEstimatedDeliveryTime(Integer shopId, String customerAddress) {
        //获取所有菜品的制作时间
        Long currentId = BaseContext.getCurrentId();
        Integer makeTimeCost = shoppingCartMapper.getMakeTimeByUserId(currentId);
        //配送时间
        Merchant merchant = merchantMapper.getShopById(shopId.longValue());
        if (merchant == null) {
            throw new ShopIDNotNULLException("找不到商家信息");
        }

        //工具类计算商家到顾客位置的距离所花费的时间(秒)
        Integer towPointCost = MapUtils.baoiduTwoPointCostTime(merchant.getShopAddress(), customerAddress);

        //预计送达时间 = 当前时间+菜品制作时间+配送时间+预留10分钟
        Integer allCostTime = makeTimeCost * 60 + towPointCost + 600;
        LocalDateTime arrivalTime = LocalDateTime.now().plusSeconds(allCostTime);

        return arrivalTime.toString();
    }

    /**
     * 用户提交订单
     *
     * @param submitDTO
     * @return
     */
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO submitDTO) {
        String key = "ORDER-CREATE:" + BaseContext.getCurrentId();
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, "aaa", Duration.ofSeconds(10));
        if (!flag) {
            log.info("没有获取到锁，不执行");
            throw new BaseException("请勿重复提交");
        }
        log.info("获取到锁,可以执行");

        Orders orders = new Orders();
        BeanUtils.copyProperties(submitDTO, orders);
        orders.setNumber(UUID.randomUUID().toString());
        orders.setUserId(BaseContext.getCurrentId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);

        orders.setAmount(submitDTO.getAmount());

        orders.setStatus(Orders.PENDING_PAYMENT);

        AddressBook addressBook = addressBookMapper.getById(submitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new BaseException("地址错误");
        }
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());
        //出餐时间，当前时间+菜品制作时间
        Integer makeTime = shoppingCartMapper.getMakeTimeByUserId(BaseContext.getCurrentId());
        orders.setMealTime(LocalDateTime.now().plusMinutes(makeTime));
        orderMapper.insert(orders);

        //插入订单详细表
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.list(shoppingCart);
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCarts) {
            OrderDetail detail = new OrderDetail();
            BeanUtils.copyProperties(cart, detail);
            detail.setOrderId(orders.getId());
            orderDetailList.add(detail);
        }
        //列表中的单价*数量
        //获取orderDetailList中的单价*数量，并返回Inteager类型

        //获取配送费

        //打包费：每件商品1元

        orderDetailMapper.insertBatch(orderDetailList);

        //清除购物车
        shoppingCartMapper.deleteByUserId(BaseContext.getCurrentId());

        OrderSubmitVO submitVO = OrderSubmitVO.builder().orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .build();

        return submitVO;
    }


    /**
     * 来单提醒
     *
     * @param number
     */
    @Override
    public void paySuccess(String number) {
        //更新订单状态
        Orders orders = orderMapper.selectByNumber(number);
        if (orders == null) {
            log.info("订单号:{}不存在，无法更新状态", number);
            return;
        }
        orders.setPayStatus(Orders.PAID);
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        orderMapper.updateOrderPaySuccess(orders);
        //发送websocket消息提醒
        Map<String, Object> map = new HashMap<>();
        map.put("type", 1);
        map.put("orderId", orders.getId());
        map.put("content", "您有新的订单了，请及时处理!");
        webSocketServer.sendOrderComeReminder(JSON.toJSONString(map));
    }


    /**
     * 用户催单
     *
     * @param id
     */
    @Override
    public void orderReminder(Long id) {
        Orders orders = orderMapper.selectById(id);
        if (orders == null) {
            log.info("订单号:{}不存在", id);
            return;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("type", 2);
        map.put("orderId", id);
        map.put("content", "用户催单，请及时处理!");
        webSocketServer.sendOrderComeReminder(JSON.toJSONString(map));
    }

    /**
     * 历史订单分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult pageQueryHistoryOrders(OrdersPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());

        List<Orders> ordersList = orderMapper.selectByStatus(dto.getStatus());
        Page<OrderVO> orderVoList = new Page<>();
        for (Orders orders : ordersList) {
            orders.setOrderDetailList(orderDetailMapper.selectByOrderId(orders.getId()));
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders, orderVO);
            orderVoList.add(orderVO);
        }
        for (OrderVO orderVO : orderVoList) {
            //查询关系表,设置订单的运单状态
            CourierTradeOrder courierTradeOrder = tradeOrderMapper.selectCourierTradeOrderByOrderNumber(orderVO.getNumber());
            if (courierTradeOrder == null) {
                orderVO.setWaybillStatus(0);
                orderVO.setCourierTelephone(null);
            } else {
                orderVO.setWaybillStatus(courierTradeOrder.getWaybillStatus());
                //设置骑手电话
                Long courierId = courierTradeOrder.getCourierId();
                Courier courier = courierMapper.selectById(courierId);
                orderVO.setCourierTelephone(courier.getTelephone());
            }
            if (orderVO.getShopId() == null) {
                orderVO.setShopName(null);
                orderVO.setShopTelephone(null);
            } else {
                //设置商品信息
                Merchant merchant = merchantMapper.selectById(orderVO.getShopId());
                orderVO.setShopName(merchant.getShopName());
                orderVO.setShopTelephone(merchant.getShopTelephone());
            }

            //设置用户信息
            User user = userMapper.getById(orderVO.getUserId());
            orderVO.setSex(user.getSex());
        }
        return new PageResult(orderVoList.getTotal(), orderVoList.getResult());
    }

    @Override
    public PageResult pageQueryRefundOrders(OrdersPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());

        List<Orders> ordersList = orderMapper.selectByStatus(dto.getPayStatus());
        Page<OrderVO> orderVoList = new Page<>();
        for (Orders orders : ordersList) {
            orders.setOrderDetailList(orderDetailMapper.selectByOrderId(orders.getId()));
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders, orderVO);
            orderVoList.add(orderVO);
        }
        for (OrderVO orderVO : orderVoList) {
            //查询关系表,设置订单的运单状态
            CourierTradeOrder courierTradeOrder = tradeOrderMapper.selectCourierTradeOrderByOrderNumber(orderVO.getNumber());
            if (courierTradeOrder == null) {
                orderVO.setWaybillStatus(0);
                orderVO.setCourierTelephone(null);
            } else {
                orderVO.setWaybillStatus(courierTradeOrder.getWaybillStatus());
                //设置骑手电话
                Long courierId = courierTradeOrder.getCourierId();
                Courier courier = courierMapper.selectById(courierId);
                orderVO.setCourierTelephone(courier.getTelephone());
            }
            if (orderVO.getShopId() == null) {
                orderVO.setShopName(null);
                orderVO.setShopTelephone(null);
            } else {
                //设置商品信息
                Merchant merchant = merchantMapper.selectById(orderVO.getShopId());
                orderVO.setShopName(merchant.getShopName());
                orderVO.setShopTelephone(merchant.getShopTelephone());
            }

            //设置用户信息
            User user = userMapper.getById(orderVO.getUserId());
            orderVO.setSex(user.getSex());
        }
        return new PageResult(orderVoList.getTotal(), orderVoList.getResult());
    }

    @Override
    public OrderVO selectOrderDetail(Long orderId) {
        Orders orders = orderMapper.selectById(orderId);
        orders.setOrderDetailList(orderDetailMapper.selectByOrderId(orderId));
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        //查询关系表,设置订单的运单状态
        CourierTradeOrder courierTradeOrder = tradeOrderMapper.selectCourierTradeOrderByOrderNumber(orderVO.getNumber());
        if (courierTradeOrder == null) {
            orderVO.setWaybillStatus(0);
            orderVO.setCourierTelephone(null);
        } else {
            orderVO.setWaybillStatus(courierTradeOrder.getWaybillStatus());
            //设置骑手电话
            Long courierId = courierTradeOrder.getCourierId();
            Courier courier = courierMapper.selectById(courierId);
            orderVO.setCourierTelephone(courier.getTelephone());
        }
        if (orderVO.getShopId() == null) {
            orderVO.setShopName(null);
            orderVO.setShopTelephone(null);
        } else {
            //设置商品信息
            Merchant merchant = merchantMapper.selectById(orderVO.getShopId());
            orderVO.setShopName(merchant.getShopName());
            orderVO.setShopTelephone(merchant.getShopTelephone());
        }
        //设置用户信息
        User user = userMapper.getById(orderVO.getUserId());
        orderVO.setSex(user.getSex());
        return orderVO;
    }

    @Override
    public void cancelOrder(Long id) throws BaseException{
        // 根据id查询订单
        Orders orders = orderMapper.selectById(id);

        // 校验订单是否存在
        if (orders == null) {
            throw new BaseException(MessageConstant.ORDER_NOT_FOUND);
        }

        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (orders.getStatus() > 2) {
            throw new BaseException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 订单处于待接单状态下取消，需要进行退款
        if (orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //调用微信支付退款接口
            WxPayController wxPayController = new WxPayController();
            wxPayController.refund();
            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }

        // 更新订单状态、取消原因、取消时间
        orders.setStatus(Orders.CANCELLED_ORDER);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.updateOrderPaySuccess(orders);
    }

    /**
     * 再来一单
     * @param id
     */
    @Override
    public void repetition(Long id) {
        List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(id);
        for (OrderDetail orderDetail : orderDetails) {
            ShoppingCartDTO shoppingCartDTO = new ShoppingCartDTO();
            BeanUtils.copyProperties(orderDetail,shoppingCartDTO);
            shoppingCartService.add(shoppingCartDTO);
        }

    }

    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(),dto.getPageSize());

        Page<OrderVO> page = orderMapper.conditionSearch(dto);

        PageResult pageResult = new PageResult();
        pageResult.setRecords(page.getResult());
        pageResult.setTotal(page.getTotal());
        return pageResult;
    }

    @Autowired
    private ThreadConfig threadConfig;
    @Override
    public OrderStatisticsVO statistics() {
//        ThreadPoolExecutor threadPoolExecutor = threadConfig.threadPool();
//
//        Future<Integer> future1 = threadPoolExecutor.submit(() -> {
//            return orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
//        });
//        Future<Integer> future2 = threadPoolExecutor.submit(() -> {
//            return orderMapper.countStatus(Orders.CONFIRMED);
//        });
//        Future<Integer> future3 = threadPoolExecutor.submit(() -> {
//            return orderMapper.countStatus(Orders.TOBEDELIVERED);
//        });
//        Future<Integer> future4 = threadPoolExecutor.submit(() -> {
//            return orderMapper.countStatus(Orders.TOBEDELIVERED);
//        });
//        Future<Integer> future5 = threadPoolExecutor.submit(() -> {
//            return orderMapper.countStatus(Orders.COMPLETE_ORDER);
//        });
//        Future<Integer> future6 = threadPoolExecutor.submit(() -> {
//            return orderMapper.countStatus(Orders.CANCELLED_ORDER);
//        });
//        Integer waiting4MerchantReceiveOrders = null;
//        Integer waitng4RiderReceiveOrders = null;
//        Integer toBeDeliveryOnProgressOrders = null;
//        Integer toBeArrivedOrders = null;
//        Integer completedOrders = null;
//        Integer canceledOrders = null;
//        try {
//            waiting4MerchantReceiveOrders = future1.get();
//            waitng4RiderReceiveOrders = future2.get();
//            toBeDeliveryOnProgressOrders = future3.get();
//            toBeArrivedOrders = future4.get();
//            completedOrders = future5.get();
//            canceledOrders = future6.get();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        return orderMapper.selectStatistics();
    }

    @Override
    public void adminCancelOrder(OrdersCancelDTO ordersCancelDTO) throws BaseException{
        Orders orders = orderMapper.selectById(ordersCancelDTO.getId());
        Integer status = orders.getStatus();

        switch (status){
            case 2:
            case 3:
            case 4:
            case 5:
                System.out.println("用户与商家沟通");
                orders.setStatus(Orders.CANCELLING);
                break;
            case 1:
            case 6:
            case 7:
            case 8:
            default:
                throw new BaseException("订单状态不正确，无法取消");
        }
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.cancelOrder(orders);
    }

    @Override
    public void rejectionOrder(OrdersRejectionDTO dto) throws BaseException{
        // 根据id查询订单
        Orders orders = orderMapper.selectById(dto.getId());

        // 校验订单是否存在
        if (orders == null) {
            throw new BaseException(MessageConstant.ORDER_NOT_FOUND);
        }

        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (orders.getStatus() !=2) {
            throw new BaseException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //支付状态
        Integer payStatus = orders.getPayStatus();
        if (payStatus == Orders.PAID) {
            //用户已支付，需要退款
            //调用微信支付退款接口
//            WxPayController wxPayController = new WxPayController();
//            wxPayController.refund();
            log.info("用户退款");
        }

        // 更新订单状态、取消原因、取消时间
        // 拒单需要退款，根据订单id更新订单状态、拒单原因、取消时间
        orders.setStatus(Orders.CANCELLING);
        orders.setRejectionReason(dto.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.updateRejectionOrder(orders);
    }


}
